import 'dart:convert';

import 'package:get/get.dart';
import 'package:zootix/models/zt_ticket.model.dart';
import 'package:zootix/services/zt_service.dart';
import 'package:zootix/util/zt_common.util.dart';
import 'package:zootix/util/zt_convert.dart';

import '../constants/zt_constants.dart';

class ZtTicketStore extends GetxController {
  static ZtTicketStore get to => Get.find();
  final ticketNumber = ''.obs;
  RxList<ZtTicketModel> myTicketList = RxList<ZtTicketModel>([]);
  Future<ZtTicketStore> init() async {
    await getTicketList();
    return this;
  }

  Future<void> generateTicketNumber(String parkType) async {
    ticketNumber.value = ZtCommonUtil.generateTicketNumber();
    myTicketList.insert(
        0,
        ZtTicketModel(
            isUsed: false,
            ticketNumber: ticketNumber.value,
            parkType: parkType));
    await ZtStorageService.to
        .setString(ZtCacheKeys.ticketList, jsonEncode(myTicketList));
  }

  Future<void> getTicketList() async {
    final ticketsCache = ZtStorageService.to.getString(ZtCacheKeys.ticketList);
    if (ticketsCache != null) {
      myTicketList.clear();
      myTicketList.addAll(toList(jsonDecode(ticketsCache))
          .map((e) => ZtTicketModel.fromJson(e))
          .toList());
    }
  }
}
